package leetcode_1601_1700;

import com.sun.org.apache.xalan.internal.xsltc.dom.SortingIterator;

import java.util.*;

public class LeeCode_1625 {
    public static void main(String[] args) {
        System.out.println(findLexSmallestString("5525", 9, 2));
        System.out.println(findLexSmallestString("74", 5, 1));
        System.out.println(findLexSmallestString("0011", 4, 2));
        System.out.println(findLexSmallestString("43987654", 7, 3));
        System.out.println(findLexSmallestString("593290172167", 7, 4));
        /*"593290172167"
        7
        4*/
    }

    private static String findLexSmallestString(String s, int a, int b) {
        Set<String> set = new TreeSet<>();
        int len = s.length();
        if(b % 2 != 0){
            //能轮转所有位置
            for (int i = 0; i < 10; i++) {
                for (int j = 0; j < 10; j++) {
                    StringBuilder sb = new StringBuilder();
                    for (int m = 0; m < len; m++) {
                        int num = s.charAt(m) - '0';
                        if (m % 2 == 0){
                            num = (num + i * a) % 10;
                        }else
                            num = (num + j * a) % 10;
                        sb.append(num);
                    }
                    String ss = sb.toString();
                    while (!set.contains(ss)){
                        set.add(ss);
                        ss = ss.substring(len - b, len) + ss.substring(0, len - b);
                    }
                }
            }
        }else {
            //只能轮转偶数位
            for (int i = 0; i < 10; i++) {
                StringBuilder sb = new StringBuilder();
                for (int m = 0; m < len; m++) {
                    int num = s.charAt(m) - '0';
                    if (m % 2 == 1){
                        num = (num + i * a) % 10;
                        sb.append(num);
                    }else
                        sb.append(num);
                }
                String ss = sb.toString();
                while (!set.contains(ss)){
                    set.add(ss);
                    ss = ss.substring(len - b, len) + ss.substring(0, len - b);
                }
            }
        }
        Iterator<String> iterator = set.iterator();
        return iterator.next();
    }
}
